<template>
  <div class="users-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="parmasinfo.query"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
        <!-- 添加用户对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogFormVisible"
          width="50%"
          @close="closeReset"
        >
          <el-form :model="userForm" :rules="userFormRule" ref="userFormRef">
            <el-form-item label="用户名" label-width="70px" prop="username">
              <el-input
                v-model="userForm.username"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" label-width="70px" prop="password">
              <el-input
                v-model="userForm.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" label-width="70px" prop="email">
              <el-input v-model="userForm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机" label-width="70px" prop="mobile">
              <el-input v-model="userForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </div>
        </el-dialog>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="usersList" style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="手机" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="updateUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="删除用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="AssignRolesVisity(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="updateUserVisible"
        width="50%"
        @close="updateUserClose"
      >
        <el-form
          :model="updatedUsers"
          :rules="updatedUsersRule"
          ref="updatedUsersRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="updatedUsers.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="updatedUsers.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="updatedUsers.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="update">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="roledialogVisible"
        width="30%"
        @close="resetRole"
      >
        <p>当前的用户：{{ userinfo.username }}</p>
        <p>当前的角色：{{ userinfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="parmasinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="parmasinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
// 导入userAPI接口
import { usersAPI } from '@/api/usersAPI.js'
// 导入switchChangeAPI接口
import { switchChangeAPI } from '@/api/switchChangeAPI.js'
// 导入addUserAPI接口
import { addUserAPI } from '@/api/addUserAPI.js'
// 导入updateUserAPI接口
import { updateUserAPI } from '@/api/updateUserAPI.js'
// 导入updateAPI接口
import { updateAPI } from '@/api/updateAPI.js'
// 导入deleteUserPAI接口
import { deleteUserAPI } from '@/api/deleteUserAPI.js'
// 导入AssignRolesAPI接口
import { AssignRolesAPI } from '@/api/AssignRolesAPI.js'
// 导入AssignRrolesListsAPI接口
import { AssignRrolesListsAPI } from '@/api/AssignRrolesListsAPI.js'
export default {
  name: 'Users',
  data() {
    // 邮箱号验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱号'))
    }
    var checkmobile = (rule, value, callback) => {
      const regEmail = /^1[3456789]\d{9}$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      // usersAPI请求参数
      parmasinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 后台响应的列表数据
      usersList: [],
      // 后台响应的列表总条数
      total: 0,
      // 控制对话框的显示隐藏
      dialogFormVisible: false,
      // 新的用户信息
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 新增用户验证规则对象
      userFormRule: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在3~10个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在6~15个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请填写邮箱号', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框显示隐藏
      updateUserVisible: false,
      // 修改用户后的数据对象
      updatedUsers: {},
      // 修改用户验证规则
      updatedUsersRule: {
        email: [
          { required: true, message: '请填写邮箱号', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      roledialogVisible: false,
      userinfo: {},
      rolesList: [],
      // 已选中的角色id值
      selectRoleId: ''
    }
  },
  methods: {
    // 获取用户列表数据
    async getUsers() {
      const { data: res } = await usersAPI(this.parmasinfo)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 每页展示的条数
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.parmasinfo.pagesize = newSize
      this.getUsers()
    },
    // 控制页码数
    handleCurrentChange(newpage) {
      // console.log(newpage)
      this.parmasinfo.pagenum = newpage
      this.getUsers()
    },
    async userStateChange(userInfo) {
      // console.log(userInfo)
      const { data: res } = await switchChangeAPI(
        userInfo.id,
        userInfo.mg_state
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 关闭添加用户对话框重置表单
    closeReset() {
      this.$refs.userFormRef.resetFields()
    },
    // 点击确定添加用户
    addUser() {
      this.$refs.userFormRef.validate(async(valid) => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await addUserAPI(this.userForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('创建用户失败')
        }
        this.$message.success('创建用户成功')
        this.getUsers()
        this.$refs.userFormRef.resetFields()
        this.dialogFormVisible = false
      })
    },
    // 修改用户数据
    async updateUser(id) {
      this.updateUserVisible = true
      // console.log(id)
      const { data: res } = await updateUserAPI(id)
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户失败')
      }
      this.updatedUsers = res.data
    },
    // 关闭对话框重置修改用户表单验证规则
    updateUserClose() {
      this.$refs.updatedUsersRef.resetFields()
    },
    // 修改用户
    update() {
      this.$refs.updatedUsersRef.validate(async(valid) => {
        if (!valid) return
        const { data: res } = await updateAPI(
          this.updatedUsers.id,
          this.updatedUsers.email,
          this.updatedUsers.mobile
        )
        if (res.meta.status !== 200) return this.$message.error('修改用户失败')
        // console.log(res)
        // 关闭表单
        this.updateUserVisible = false
        // 关闭对话框后重置表单验证
        this.$refs.updatedUsersRef.resetFields()
        // 重新渲染列表数据
        this.getUsers()
        // 提示修改成功
        this.$message.success('修改用户数据成功')
      })
    },
    // 删除用户
    async deleteUser(id) {
      // console.log(id)
      const result = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果返回的是字符串confirm表示确定
      // 如果返回的是字符串cancel表示取消
      // console.log(result)
      if (result !== 'confirm') return this.$message.info('删除已取消')
      const { data: res } = await deleteUserAPI(id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.getUsers()
    },
    // 分配角色对话框显示
    async AssignRolesVisity(userinfo) {
      console.log(userinfo.id)
      this.userinfo = userinfo
      const { data: res } = await AssignRolesAPI()
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.roledialogVisible = true
    },
    // 分配角色
    async setRole() {
      console.log(this.selectRoleId)
      const { data: res } = await AssignRrolesListsAPI(
        this.userinfo.id,
        this.selectRoleId
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUsers()
      this.roledialogVisible = false
    },
    // 关闭对话框重置对话框中的角色信息和选项
    resetRole() {
      this.selectRoleId = ''
      this.userinfo = {}
    }
  },
  created() {
    // 当props，data，methods创建好就获取用户列表数据
    this.getUsers()
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-pagination {
  margin-top: 15px;
}
</style>
